package com.dff.jrfw.remote;


import com.bumptech.glide.load.HttpException;
import com.dff.jrfw.utils.ToastUtil;

import java.net.ConnectException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Description: 网络请求回调封装类
 */
public abstract class RequestCallBack<T> implements Callback<BaseModel<T>> {

    public RequestCallBack() {
    }

    protected abstract void onSuccess(T t);

    protected void onFailed(int code, String msg) {
    }

    @Override
    public void onResponse(Call<BaseModel<T>> call, Response<BaseModel<T>> response) {
        BaseModel<T> baseModel = response.body();
        if (response.isSuccessful() && baseModel != null) {
            if (baseModel.code == 200) {
                onSuccess(baseModel.data);
            } else {
                ToastUtil.toast(baseModel.msg);
                onFailed(baseModel.code, baseModel.msg);
            }
        } else {
            ToastUtil.toast(response.message());
            onFailed(response.code(), response.message());
        }
    }

    @Override
    public void onFailure(Call<BaseModel<T>> call, Throwable t) {
        if (t instanceof ConnectException) {
            //网络连接失败
            onFailed(403, t.getMessage());
        } else if (t instanceof HttpException) {
            HttpException ex = (HttpException) t;
            onFailed(ex.getStatusCode(), ex.getMessage());
        } else {
            onFailed(405, t.getMessage());
        }
    }

}
